const Wxa = require("./../../../../lib/wxa/wxa.class");
const moment = require("moment");

module.exports = class extends doodoo.Controller {
    async getCustomInfo() {
        const custom = await this.isCustomAuth();
        if (custom) {
            const custom = await this.model("custom")
                .query({ where: { id: this.state.custom.id } })
                .fetch({ withRelated: ["wx_user"] });
            this.success(custom);
        }
    }

    async getAppInfo() {
        const app = await this.isAppAuth();
        if (app) {
            this.success(app);
        }
    }

    async getAppValid() {
        const app = await this.isAppAuth();
        if (app) {
            const template = await this.model("template")
                .query({
                    where: {
                        id: app.template_id
                    }
                })
                .fetch();
            this.success({
                name: app.name,
                started_at: moment(app.started_at).format(
                    "YYYY-MM-DD HH:mm:ss"
                ),
                ended_at: moment(app.ended_at).format("YYYY-MM-DD HH:mm:ss"),
                valid_days: moment(app.ended_at).diff(moment(), "days"),
                price: template.price,
                price_tag: template.price_tag,
                old_price: template.old_price
            });
        }
    }

    async getWxaPathQrcode() {
        const { path, width, type } = this.query;
        const wxa = await this.isWxaAuth();
        if (wxa) {
            const wxaObj = new Wxa(
                process.env.OPEN_APPID,
                process.env.OPEN_APPSECRET
            );
            const wxa = await this.checkWxaAuthorizerAccessToken(
                this.state.wxa
            );

            this.body = wxaObj.getWxaQrcode(
                wxa.authorizer_access_token,
                path,
                width,
                type
            );
        }
    }

    async getWxaInfo() {
        const wxa = await this.isWxaAuth();
        const custom = await this.isCustomAuth();

        if (wxa && custom) {
            this.success(wxa);
        }
    }

    // async getWxaPathQrcode() {
    //     const custom = await this.isCustomAuth();
    //     const wxa = await this.isWxaAuth();

    //     if (custom && wxa) {
    //         const { path, width, type } = this.query;
    //         const wxaObj = new Wxa(
    //             process.env.OPEN_APPID,
    //             process.env.OPEN_APPSECRET
    //         );
    //         const wxa = await this.checkWxaAuthorizerAccessToken(
    //             this.state.wxa
    //         );

    //         this.body = wxaObj.getWxaQrcode(
    //             wxa.authorizer_access_token,
    //             path,
    //             width,
    //             type
    //         );
    //     }
    // }

    async isCustomAuth() {
        try {
            const Token = this.query.Token || this.get("Token");
            if (!Token) {
                this.status = 401;
                this.fail("授权失败", "Custom Unauthorized");
                return false;
            }

            const decoded = this.jwtVerify(Token);
            const custom = await this.model("custom")
                .query({ where: { id: decoded.id } })
                .fetch();
            if (!custom) {
                this.status = 401;
                this.fail("用户未授权", "Custom Unauthorized");
                return false;
            }
            if (!custom.status) {
                this.status = 401;
                this.fail("用户被禁用", "Custom Status Unauthorized");
                return false;
            }

            return (this.state.custom = custom);
        } catch (err) {
            this.status = 401;
            this.fail("授权失败", "Custom Unauthorized");
            return false;
        }
    }

    async isWxaAuth() {
        try {
            let app = this.state.app;
            if (!app) {
                app = await this.isAppAuth();
            }
            if (!app) {
                this.status = 401;
                this.fail("授权失败", "App Unauthorized");
                return;
            }
            const wxa = await this.model("wxa")
                .query({
                    where: {
                        app_id: app.id
                    }
                })
                .fetch();
            if (!wxa) {
                this.status = 200;
                this.fail("小程序未授权", "Wxa Unauthorized");
                return false;
            }
            if (!wxa.authorized) {
                this.status = 200;
                this.fail("小程序已取消授权", "Wxa Has Been Unauthorized");
                return false;
            }
            if (!wxa.status) {
                this.status = 200;
                this.fail("小程序被禁用", "Wxa Status Unauthorized");
                return false;
            }

            return (this.state.wxa = wxa);
        } catch (err) {
            this.status = 200;
            this.fail("授权失败", "Wxa Unauthorized");
            return false;
        }
    }

    async isAppAuth() {
        try {
            const AppToken = this.query.AppToken || this.get("AppToken");
            if (!AppToken) {
                this.status = 401;
                this.fail("授权失败", "App Unauthorized");
                return false;
            }

            const decoded = this.jwtVerify(AppToken);
            const app = await this.model("app")
                .query({
                    where: {
                        id: decoded.id
                    }
                })
                .fetch();
            if (!app) {
                this.status = 401;
                this.fail("应用未授权", "App Unauthorized");
                return false;
            }

            return (this.state.app = app);
        } catch (err) {
            this.status = 401;
            this.fail("授权失败", "App Unauthorized");
            return false;
        }
    }
};
